package com.example.cardgame.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.example.cardgame.utils.CardAdapter
import com.example.cardgame.R
import com.example.cardgame.model.UserInfo
import com.example.cardgame.databinding.FragmentTwoCardGameBinding
import com.example.cardgame.model.TwoCardMatchingGame
import com.example.cardgame.utils.FileUtils.loadUserInfo
import com.example.cardgame.utils.FileUtils.saveUserInfo
import java.io.ObjectInputStream
import java.io.ObjectOutputStream

class TwoCardGameFragment : Fragment() {
    private var _binding: FragmentTwoCardGameBinding? = null
    private val binding get() = _binding!!
    private lateinit var adapter: CardAdapter<TwoCardMatchingGame>
    private val fileName = "user_info.dat"
    companion object {
        val game = TwoCardMatchingGame(20)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentTwoCardGameBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        adapter = CardAdapter(game)
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager = GridLayoutManager(context, 4)
        adapter.setOnClickListener {
            game.chooseCardAtIndex(it)
            updateUI()
        }
        updateUI()
        
        binding.buttonReset.setOnClickListener {
            game.reset()
            updateUI()
        }

        binding.buttonExit.setOnClickListener {
            val userInfo = loadUserInfo(requireContext(), fileName) ?: UserInfo("N/A", "N/A", "N/A", "N/A", "N/A", "N/A", 0, 0)
            if (game.score > userInfo.score2) {
                userInfo.score2 = game.score
                saveUserInfo(requireContext(), fileName, userInfo)
            }
            game.reset()
            Toast.makeText(context, "游戏结束", Toast.LENGTH_SHORT).show()
            parentFragmentManager.beginTransaction()
                .replace(R.id.fragment_container, PersonalInfoFragment())
                .commit()
        }
    }

    private fun updateUI() {
        adapter.notifyDataSetChanged()
        binding.textScore.text = String.format("%s%d", getString(R.string.score_prefix), game.score)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}